import React, { Component } from 'react'
import { TextArea ,Input,Button,Checkbox,NavBar} from 'antd-mobile'
import {  Space,Toast} from 'antd-mobile'
import axios from "../../../../http";
import Qs from 'qs'
import { DemoBlock } from "../../../../demos/demo-block/index.tsx";
import {Tree} from "antd";
import {DownOutlined} from "@ant-design/icons";
import {convertData} from "./CategoryTreeDataUtils";
import { withRouter } from 'react-router';
class NoteAdd extends Component {
    constructor(props){
        super(props)
        this.state={autoSave:true,data:[],categorySelectedKeys:[],title:'unnamed',id:''}
    }
    // 原生事件

    autoSaveChange=()=>{
        console.log(this.state.autoSave)
        if(this.state.autoSave==true){
            this.setState({autoSave:false})
        }else {
            this.setState({autoSave:true})
        }

    }
    onRecordChange = (value) => {
        let state={};
        state['title']=value;
        this.setState(state)
    };

    
    categoryOnSelect = (selectedKeys, info) => {
        this.setState({categorySelectedKeys:selectedKeys})
    }
    // 读取数据
    add=() =>{
        let categoryId=this.getCategoryId();
        let entity={'title':this.state.title,'categoryId':categoryId,content:this.state.content};
        axios.post('api/oa/note/add', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.showSuccessMessage(data.message)
                }else{
                    this.showErrorMessage(data.message);
                }
                this.setState({id:data.data})
            })
            .catch(function (error) {
                console.log(error);
            });

    }
    loadData=() =>{
        axios.post('api/oa/note/category/findMyAll', Qs.stringify({
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{

                let  data=response.data

                let list=data.data

                list=convertData(list,0);

                this.setState({data:list});
            })
            .catch(function (error) {
                console.log(error);
            });

    }
    autoAdd=() =>{
        if(this.state.title==''||this.state.content==''){
            return ;
        }
        let categoryId=this.getCategoryId();
        let entity={'title':this.state.title,'categoryId':categoryId,content:this.state.content};
        axios.post('api/oa/note/add', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.showSuccessMessage('已自动保存！')
                }else{
                    this.showErrorMessage(data.message);
                }
                this.setState({id:data.data})
            })
            .catch(function (error) {
                console.log(error);
            });

    }


    autoUpdate=() =>{
         if(this.state.title==''||this.state.content==''){
             return ;
         }
        let categoryId=this.getCategoryId();
        let entity={'title':this.state.title,'categoryId':categoryId,content:this.state.content,id:this.state.id};
        axios.post('api/oa/note/update', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.showSuccessMessage('已自动保存！')
                }else{
                    this.showErrorMessage(data.message);
                }
            })
            .catch(function (error) {
                console.log(error);
            });
    }

    //功能函数
    
    getCategoryId=()=>{
        let categorySelectedKeys=this.state.categorySelectedKeys;
        if(categorySelectedKeys.length==0){
            return null;
        }
        let categorySelectedKey=categorySelectedKeys[0];
        let categoryId=categorySelectedKey.substring(4,categorySelectedKey.length);
        return categoryId;
    }
    showSuccessMessage (systemMessage){
        // message.success(
        //     <MessageContent>
        //         {systemMessage}
        //     </MessageContent>,
        //     5
        // );
        Toast.show({
            content:  systemMessage,
            afterClose: () => {
                console.log('after')
              },
            
          })
    };
    showErrorMessage (systemMessage){
        // message.error(
        //     <MessageContent>
        //         {systemMessage}
        //     </MessageContent>,
        //     5
        // );
        Toast.show({
            content:  systemMessage,
            afterClose: () => {
                console.log('after')
              },
            
          })
    };
    goBack=()=>{
        
        this.props.history.push({pathname:"/note"})
    }
   
    //生命周期函数和时间函数
    componentDidMount() {
        this.loadData()
        this.timer = setInterval(
            () => {
                if(this.state.autoSave==true){
                    if(this.state.id!=""){
                        this.autoUpdate();
                    }else {
                        this.autoAdd();
                    }
                }
            },
            10000
        );
    }

    componentWillUnmount() {
        this.timer && clearTimeout(this.timer);
    }
    //render
    render() {
        const {autoSave}=this.state
        return (
            <div>
                <NavBar onBack={this.goBack}>新建笔记</NavBar>
                <DemoBlock title='自动保存'>
                <Space direction='vertical'>
                <Checkbox checked={autoSave} onChange={this.autoSaveChange}>自动保存</Checkbox>
                </Space>
                </DemoBlock>
                <DemoBlock title='标题'>
                <Input placeholder='请输入标题'
                value={this.state.title} 
                onChange={this.onRecordChange}
                 />
                </DemoBlock>
                <DemoBlock title='分类'>
                <Tree
                            switcherIcon={<DownOutlined />}
                            onSelect={this.categoryOnSelect}
                            selectedKeys={this.state.categorySelectedKeys}
                            treeData={this.state.data}
                />
                </DemoBlock>
                <DemoBlock title='内容'>
                 <TextArea
                    placeholder='请输入内容'
                    value={this.state.content}
                    onChange={(value)=>{this.setState({content:value})}}
                    autoSize={{ minRows: 3, maxRows: 5 }}
                    showCount
                    maxLength={300}/>
                </DemoBlock>
                <DemoBlock title='提交'>
                <Button block color='primary' size='large' onClick={this.add}>
                            提交
                </Button>
                </DemoBlock>
            </div>
        )
    }
}
export default withRouter(NoteAdd)